package com.hnx.admin.aurora.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

/*
创建人： 倔强的头发
创建时间：2025/6/15
功能描述:

*/
public class ServletUtil {
    public static final String JSON = "application/json";
    public static ServletRequestAttributes getRequestAttributes()
    {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }
    /**
     * 获取request
     */
    public static HttpServletRequest getRequest()
    {
        try {
            return getRequestAttributes().getRequest();
        }catch (Exception ex){
            return null;
        }
    }
    /**
     * 返回数据给客户端
     *
     * @param response    响应对象{@link HttpServletResponse}
     * @param text        返回的内容
     * @param contentType 返回的类型
     */
    public static void write(HttpServletResponse response, String text, String contentType) {
        response.setContentType(contentType);
        Writer writer = null;
        try {
            writer = response.getWriter();
            writer.write(text);
            writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                writer.close();
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
    }
    public static void write(HttpServletResponse response, String text){
        write(response,text,JSON);
    }
}
